<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    dataBarSet: { type: Object as () => any, required: true },
    dataBarReal: { type: Object as () => any, required: true },
    dataLine: { type: Object as () => any, required: true },
    datax: { type: Object as () => any, required: true },
    yAxisNmae: { type: Object as () => any, default: ['', ''] },
    dataName: { type: Object as () => any, default: ['', '', ''] },
    title: { type: String, default: '' },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option = {
    title: {
      text: props.title, // 图表标题
      left: 'center', // 标题居中
      textStyle: {
        fontSize: 14,
        fontWeight: 'bold',
      },
    },
    tooltip: {
      trigger: 'axis', // 坐标轴触发 tooltip
      axisPointer: { type: 'cross' }, // 十字准星指示
      appendToBody: true, // 关键设置
      // confine: true,
      position: function (point: any) {
        return [point[0], point[1] + 20]; // 将提示框向下偏移20像素
      },
      formatter: function (params: any) {
        if (!Array.isArray(params) || params.length === 0) return '';
        const dot = (color: string) =>
          `<span style="display:inline-block;width:10px;height:10px;background-color:${color};border-radius:50%;margin-right:5px;"></span>`;

        let header = '';
        const rows: { label: string; value: string }[] = [];
        params.forEach((item: any) => {
          const isPercent = item.seriesName === '达成率' || item.seriesName === '利用率';
          if (item.seriesName === '预测') {
            header = item.name;
          }
          const valueText = isPercent ? `${item.value}%` : `${item.value}`;
          rows.push({ label: `${dot(item.color)}${item.seriesName}`, value: valueText });
        });

        const table = `<table style="border-collapse:collapse;">
          ${rows
            .map(
              (r) =>
                `<tr>
                  <td style="padding:0 10px 0 0;white-space:nowrap;">${r.label}</td>
                  <td style="text-align:right;white-space:nowrap;">${r.value}</td>
                </tr>`
            )
            .join('')}
        </table>`;
        return `${header ? `${header}<br/>` : ''}${table}`;
      },
    },
    legend: {
      data: props.dataName, // 对应 series 的 name，按需修改
      top: props.title == '' ? '0%' : '10%', // 图例位置
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true, // 让 grid 包含坐标轴文本
    },
    xAxis: {
      type: 'category',
      data: props.datax ?? [], // X 轴类目
    },
    yAxis: [
      {
        type: 'value',
        name: props.yAxisNmae[0],
        scale: true,
        axisLabel: {
          formatter: '{value}',
        },
      },
      {
        type: 'value',
        name: props.yAxisNmae[1],
        scale: true,
        axisLabel: {
          formatter: '{value}' + '%',
        },
        position: 'right', // 右侧 Y 轴
      },
    ],
    series: [
      {
        name: props.dataName[0],
        type: 'bar',
        data: props.dataBarSet ?? [],
        yAxisIndex: 0,
        itemStyle: {
          color: '#ff9c39',
          borderRadius: [8, 8, 8, 8],
          opacity: 0.9,
        },
      },
      {
        name: props.dataName[1],
        type: 'bar',
        data: props.dataBarReal ?? [],
        yAxisIndex: 0,
        itemStyle: {
          color: '#029cc7',
          borderRadius: [8, 8, 8, 8],
          opacity: 0.9,
        },
      },
      {
        name: props.dataName[2],
        type: 'line',
        data: props.dataLine ?? [],
        yAxisIndex: 1,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: '#91cc75',
        },
      },
    ],
  };

  const initCharts = () => {
    try {
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    option.title.text = props.title;
    option.series[0].data = props.dataBarSet ?? [];
    option.series[1].data = props.dataBarReal ?? [];
    option.series[2].data = props.dataLine ?? [];
    option.xAxis.data = props.datax ?? [];
    chartInstance?.setOption(option, true);
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    // window.removeEventListener('resize', updateChart);
    window.removeEventListener('resize', handleResize);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.dataBarSet, props.dataBarReal, props.dataLine],
    () => updateChart(),
    { deep: true }
  );

  watch(
    () => props.title,
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
  });

  // 窗口大小变化处理
  const handleResize = () => {
    nextTick(() => {
      chartInstance?.resize();
    });
  };
</script>
<template>
  <div ref="chartRef" class="chart-container">
    <!-- <m-echarts :option="option"></m-echarts> -->
  </div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
